<?php

namespace Home\Controller;

class PaynotifyController extends BaseMallController {

    /**
     * @api {get} /index.php?m=Home&c=Paynotify&a=index 线上支付通知
     */
    function index() {
        $out_trade_no = I('post.out_trade_no');
        $total_fee = I('post.total_fee');
        $sign = I('post.sign');
        if (empty($out_trade_no) || empty($total_fee)) {
            return;
        }

        $time = time();
        //根据用户订单号，获取充值者的ID
        $account_log = M('AccountLog')->where("money_flow = 'income' AND order_sn='" . $out_trade_no . "' AND money=" . $total_fee)->find();

        if (empty($account_log) || $account_log['complete'] == '1') {
            return;
        }

        $user_id = $account_log['user_id'];
        //获取用户的余额
        $row_member = M('Member')->where("user_id='$user_id'")->find();
        if (!$row_member) {//不存在，则结束
            //修改记录
            $edit_account_log = array(
                'add_time' => $time,
                'money' => 0,
                'complete' => 1,
                'states' => 61,
                'log_text' => '用户不存在，其充值的' . $total_fee . '元存在平台账户中',
            );
            M('AccountLog')->where('order_sn=' . '"' . $out_trade_no . '"')->save($edit_account_log);
            return;
        }
        $valid_ok = false;
        //查找此token
        $tokens = M('AppToken')->where('m.user_id=' . $account_log['user_id'])->alias('at')->join('LEFT JOIN ' . C('DB_PREFIX') . 'member m ON m.user_id = at.user_id')->field('m.user_id,token,available,password')->select();
        if ($tokens) {
            foreach ($tokens as $token) {
                //验证token
                if (md5(MODULE_NAME . CONTROLLER_NAME . ACTION_NAME . $token['token']) == $sign) {

                    $valid_ok = true;
                }
            }
        }
        if (!$valid_ok) {
            //修改记录
            $edit_account_log = array(
                'add_time' => $time,
                'money' => 0,
                'complete' => 1,
                'states' => 61,
                'log_text' => '用户验证失败，其充值的' . $total_fee . '元存在平台账户中',
            );
            M('AccountLog')->where('order_sn=' . '"' . $out_trade_no . '"')->save($edit_account_log);
            return;
        }
        //计算新的余额
        $old_money = $row_member['money'];
        $new_money = $old_money + $total_fee;
        $edit_money = array(
            'money' => $new_money,
        );
        M('Member')->where('user_id=' . $user_id)->save($edit_money);
        //修改记录
        $edit_account_log = array(
            'add_time' => $time,
            'money' => $total_fee,
            'complete' => 1,
            'states' => 61,
        );
        M('AccountLog')->where('order_sn=' . '"' . $out_trade_no . '"')->save($edit_account_log);
        $order_id_array = array();
        if (!empty($account_log['orders_group'])) {
            $order_id_array = explode(',', $account_log['orders_group']);
        } else {
            $account_log['order_id'] && $order_id_array = array($account_log['order_id']);
        }
        //---------------------  以下是判断  是否启用 自动付款----------------------


        foreach ($order_id_array as $order_id) {
            //根据用户返回的 order_sn 判断是否为订单
            $order_info = M('Order')->where('order_id=' . $order_id)->find();

            if (!empty($order_info)) {
                if (!M('Member')->where('user_id=' . $order_info['seller_id'])->find()) {
                    return;
                }
                //如果存在订单号  则自动付款
                //买家扣除金额
                $buyer_data = array(
                    'user_id' => $order_info['buyer_id'],
                    'user_name' => $order_info['buyer_name'],
                    'order_id' => $order_id,
                    'order_sn ' => $order_info['order_sn'],
                    'add_time' => $time,
                    'type' => ACCOUNT_TYPE_BUY,
                    'money_flow' => 'outlay',
                    'money' => $order_info['order_amount'],
                    'log_text' => '购买商品店铺:' . $order_info['seller_name'],
                );
                if (!$account_log_id = D('Accountlog')->change_money($buyer_data)) {
                    return;
                }

                //卖家对资金进行操作，新增记录同时把金额加入冻结资金
                $seller_data = array(
                    'user_id' => $order_info['seller_id'],
                    'user_name' => '',
                    'order_id' => $order_id,
                    'order_sn ' => $order_info['order_sn'],
                    'add_time' => $time,
                    'type' => ACCOUNT_TYPE_SELLER,
                    'money_flow' => 'income',
                    'money' => $order_info['order_amount'],
                    'log_text' => '出售商品买家:' . $order_info['buyer_name'],
                );
                if (!$account_log_id = D('Accountlog')->change_money($seller_data, 'money_dj')) {
                    return;
                }
                //更新定单状态
                $order_edit_array = array(
                    'status' => 20, //20就是 待发货了
                );
                D('Order')->where('order_id=' . $order_id)->save($order_edit_array);
            }
        }
    }

    /**
     * @api {get} /index.php?m=Home&c=Paynotify&a=wxpay 线上支付通知
     */
    function wxpay() {
        import('Mall.Payment.Wxpay.WxPayment','','.php');
        $payment = new \WxPayment();
        $notify_result  = $payment->verify_notify();
        if ($notify_result['trade_status']) {
            $this->_change_status($notify_result);
        }
    }
    /**
     * @api {get} /index.php?m=Home&c=Paynotify&a=alipay 支付宝支付通知
     */
    function alipay() {
        import('Mall.Payment.Alipay.AliPayment','','.php');
        $payment = new \AliPayment();
        $notify_result  = $payment->verify_notify();
        if ($notify_result['trade_status']) {
            $this->_change_status($notify_result);
        }
    }

    function _change_status($notify_result) {
        extract($notify_result);
        if (empty($out_trade_no) || empty($total_fee)) {
            
            return;
        }
        
        $time = time();
        $member_mod = M('member');
        $account_log_mod = M('account_log');
        //根据用户订单号，获取充值者的ID
        $account_log = $account_log_mod->where("money_flow = 'income' AND order_sn='$out_trade_no' AND money=$total_fee")->find();
        if (empty($account_log) || $account_log['complete'] == '1') {
            return;
        }
        
        $user_id = $account_log['user_id'];
        //获取用户的余额
        $row_member = $member_mod->where("user_id='$user_id'")->find();
        if (!$row_member) {//不存在，则结束
            //修改记录
            $edit_account_log = array(
                'add_time' => $time,
                'money' => 0,
                'complete' => 1,
                'states' => 61,
                'log_text' => '用户不存在，其充值的' . $total_fee . '元存在平台账户中',
            );
            $account_log_mod->where('order_sn=' . '"' . $out_trade_no . '"')->save($edit_account_log);
            return;
        }
        //计算新的余额
        $old_money = $row_member['money'];
        $new_money = $old_money + $total_fee;
        $edit_money = array(
            'money' => $new_money,
        );
        $member_mod->where('user_id=' . $user_id)->save($edit_money);
        //修改记录
        $edit_account_log = array(
            'add_time' => $time,
            'money' => $total_fee,
            'complete' => 1,
            'states' => 61,
        );
        
        $account_log_mod->where('order_sn=' . '"' . $out_trade_no . '"')->save($edit_account_log);
        $order_id_array = array();
        if (!empty($account_log['orders_group'])) {
            $order_id_array = explode(',', $account_log['orders_group']);
        } else {
            $account_log['order_id'] && $order_id_array = array($account_log['order_id']);
        }
        //---------------------  以下是判断  是否启用 自动付款----------------------
        
        $order_mod = M('order');
        foreach ($order_id_array as $order_id) {
            //根据用户返回的 order_sn 判断是否为订单
            $order_info = $order_mod->where('order_id=' . $order_id)->find();

            if (!empty($order_info)) {
                if (!$member_mod->where('user_id='.$order_info['seller_id'])->find()) {
                    return;
                }
                //如果存在订单号  则自动付款
                //买家扣除金额
                $buyer_data = array(
                    'user_id' => $order_info['buyer_id'],
                    'user_name' => $order_info['buyer_name'],
                    'order_id' => $order_id,
                    'order_sn ' => $order_info['order_sn'],
                    'add_time' => $time,
                    'type' => ACCOUNT_TYPE_BUY,
                    'money_flow' => 'outlay',
                    'money' => $order_info['order_amount'],
                    'log_text' => '购买商品店铺:' . $order_info['seller_name'],
                );
                if (!$account_log_id = D('Accountlog')->change_money($buyer_data)) {
                    return;
                }

                //卖家对资金进行操作，新增记录同时把金额加入冻结资金
                $seller_data = array(
                    'user_id' => $order_info['seller_id'],
                    'user_name' => '',
                    'order_id' => $order_id,
                    'order_sn ' => $order_info['order_sn'],
                    'add_time' => $time,
                    'type' => ACCOUNT_TYPE_SELLER,
                    'money_flow' => 'income',
                    'money' => $order_info['order_amount'],
                    'log_text' => '出售商品买家:' . $order_info['buyer_name'],
                );
                if (!$account_log_id = D('Accountlog')->change_money($seller_data, 'money_dj')) {
                    return;
                }

                //更新定单状态
                $order_edit_array = array(
                    'status' => 20, //20就是 待发货了
                    'pay_time' => time()
                );
                $order_mod->where('order_id='.$order_id)->save($order_edit_array);
            }
        }
    }

}
